<?php
	require '../../include/library.inc.php';
	require '../../include/admin_login.inc.php';
		
if (!isset($_POST['is_submitted'])) {
	$_POST['is_submitted'] = '';
}
if (!isset($error_message)) {
	$error_message = '';
}	


$redirect = $_SERVER['HTTP_REFERER'];	
	
	if ($_POST['is_submitted']) {
		$error_message = '';
		$redirect = $_POST["redirect"];
    
	$sql = 'SELECT lang_id,Name,code FROM language WHERE published';
	$result_lang = query($sql);
	
	while ($row_lang = mysql_fetch_object($result_lang)) {
				$em = $row_lang->lang_id;
				eval('$name =  $_POST[\'title_'.$em.'\'];');
				if (!$name)  $error_message .= 'Не е въведено заглавие на '.$row_lang->Name.'<br/>';
				
				eval('$meta_d =  $_POST[\'meta_description_'.$em.'\'];');
				if (!$meta_d)  $error_message .= 'Не е въведено мета описание на '.$row_lang->Name.'<br/>';
	}
	if (!$_POST['pdf'])  $error_message .= 'Не е избран файл с описание!<br/>';
	
	
	
	if (!$_POST['seo_url'])  $error_message .= 'Не е въведено SEF URL<br/>';
		elseif(!preg_match('/^[0-9A-Za-z\-\_]+$/', $_POST['seo_url'])) $error_message .= 'Въведеният SEF URL е невалиден<br/>';
		
	$sql = "SELECT
				catalog_id
			FROM
				catalog
			WHERE
				sef_url = '".$_POST['seo_url']."'
			  ";
	$result = query($sql);
	if ($row_seo = mysql_fetch_object($result)) $error_message .= 'Въведеният SEF URL вече е използван<br/>';
	
	
	
	
	//ОК
    if(!$error_message) {
		
		$upload_path = "../catalogimage/";
		
		$sql = 'SELECT MAX(order_number)+1 AS order_number FROM catalog';
		$row_number = mysql_fetch_assoc(query($sql));
		
		//Създаваме проекта
		$sql = 'INSERT INTO catalog
				  (sef_url,  published, order_number)
				VALUES
				  (\''.escape($_POST['seo_url']).'\', \''.intval($_POST['published']).'\', \''.$row_number['order_number'].'\')
				  ';
		query($sql);
		
		
		$id = mysql_insert_id();
		$sql = 'SELECT lang_id,Name,code
				FROM
				language
				WHERE
				published
					';
		$result_lang = query($sql);
		
		while ($row_lang = mysql_fetch_object($result_lang)) {
			
				$em = $row_lang->lang_id;
				eval('$name =  $_POST[\'title_'.$em.'\'];');
				eval('$description =  $_POST[\'description_'.$em.'\'];');
				eval('$meta_k =  $_POST[\'meta_key_'.$em.'\'];');
				eval('$meta_d =  $_POST[\'meta_description_'.$em.'\'];');
			
			$sql = "INSERT INTO catalog_description
				  (catalog_id, lang_id, title, description, meta_key, meta_description)
				VALUES
				  ('".$id."','".$em."', '".escape($name)."', '".escape($description)."', '".escape($meta_k)."', '".escape($meta_d)."')";
				 
		query($sql);
		}
		
		
		
		
		// Връзка с категория
		/*if($_POST['category_id'])
		{
			$category_id = $_POST['category_id'];
		  
			foreach ($category_id as $key => $value) {
			
				$sql = 'INSERT INTO catalog_to_category
							  (catalog_id,category_id)
							VALUES
							  ('.$id.','.intval($value).')
							  ';
				query($sql);
			
			}
		}*/
		
		// pdf
		$upload_path = "../pdf/";
		if (is_uploaded_file($_FILES['pdf']['tmp_name'])) {
			$tmp_file = $_FILES['pdf']['tmp_name'];
			$exp = explode('.',$_FILES['pdf']['name']);
			$doc_type = strtolower(end($exp));
			
			$new_name = "product_".$id.".".$doc_type;
			if(copy($tmp_file, $upload_path.$new_name)) {
				
				$sql = "UPDATE catalog
						SET
				doc_description = '$new_name'
						WHERE catalog_id = '$id'";
				query($sql);
				
			} else{
				
				$_SESSION['message'] .= 'Грешка при качване на снимка. ';
				
			}
		}
		
		$_SESSION['message'] .= 'Артикулът е добавен успешно!';
        redirect('catalog_edit.php?catalog_id='.$id);
    }

}
  	
	
	head_admin("Добавяне на нов артикул");
?>
<script type="text/javascript" src="<?=HTML_BASE_ADMIN?>js/calendarDateInput.js"></script>
<script type="text/javascript" src="<?=HTML_BASE_ADMIN?>tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
	// General options
	language : "bg", 
	mode : "exact",
    elements : "body1,body2,body3,body4,body5",
	theme : "advanced",
	relative_urls : false,
	plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager",

	// Theme options
	theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect",
	theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
	theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen,|,image,insertimage",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	theme_advanced_statusbar_location : "bottom",
	theme_advanced_resizing : false,
	
	content_css : "css/editor_style.css"
	// Drop lists for link/image/media/template dialogs
	//template_external_list_url : "js/template_list.js",
	//external_link_list_url : "js/link_list.php",
	//media_external_list_url : "js/media_list.js",
	//external_image_list_url : "js/blog_image_list.php"
	
});
</script>
<?php if ($error_message) { ?>

<div class="message red">
  <h3>Грешка!</h3>
  <?=$error_message?>
</div>
<?php } ?>
<div class="topbuttons"> <a href="<?=$redirect?>">Обратно</a> </div>
<h3>Добавяне на нов артикул</h3>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data">
  <input type="hidden" name="is_submitted" value="1" />
  <input type="hidden" name="redirect" value="<?=$redirect?>" />
  <?php 
			
			$sql = 'SELECT lang_id,Name,code
					FROM language
					WHERE published';
			$result = query($sql);
			
			$i=0;
			while ($row_lang = mysql_fetch_object($result)) {
				
				
				$em = $row_lang->lang_id;
				eval('$name =  $_POST[\'title_'.$em.'\'];');
				eval('$description =  $_POST[\'description_'.$em.'\'];');
				eval('$meta_k =  $_POST[\'meta_key_'.$em.'\'];');
				eval('$meta_d =  $_POST[\'meta_description_'.$em.'\'];');
				
				  
			?>
  <dl class="clearfix">
    <h3>Данни на
      <?=$row_lang->Name?>
    </h3>
    <dt>
      <label class="required">Заглавие на
        <?=$row_lang->Name?>
      </label>
    </dt>
    <dd>
      <input class="inputbox w500" name="title_<?=$row_lang->lang_id?>" type="text" value="<?=$name?>" >
    </dd>
    <dt>
      <label>Описание на
        <?=$row_lang->Name?>
      </label>
    </dt>
    <dd>
      <textarea id="body<?=$row_lang->lang_id?>"  class="inputbox" style="width:100%" name="description_<?=$row_lang->lang_id?>" rows="20"><?=sth($description)?>
</textarea>
    </dd>
    <dl style="float:left;">
      <dt>
        <label >Мета описание </label>
      </dt>
      <dd>
        <textarea class="inputbox w400" name="meta_description_<?=$row_lang->lang_id?>" rows="3" ><?=$meta_d?>
</textarea>
      </dd>
    </dl>
    <dl>
      <dt>
        <label >Ключови думи  (до 110 символа)</label>
      </dt>
      <dd>
        <textarea class="inputbox w400" name="meta_key_<?=$row_lang->lang_id?>" rows="3" maxlength="110"><?=$meta_k?>
</textarea>
      </dd>
    </dl>
  </dl>
  <?php
				$i++;
			}
			
	  		?>
            <?php
  /*<dl>
    <dt>
      <label >Категория</label>
    </dt>
    <dd>
      <ul class="type-box">
        <?php         
			$sql_c = "SELECT
			c.category_id,
			d.Name
			
		FROM
			category AS c,
			category_description AS d
		WHERE
		
			c.category_id = d.category_id
			
			AND
			
			d.lang_id = '1'
			
			AND
			c.published
			
			ORDER BY c.order_number DESC
			
		  ";
		
			$result_c = query($sql_c);
			$i = 1;	
			while ($row = mysql_fetch_object($result_c)) {
				  ?>
        <li>
          <label>
            <input class="checkbox" name="category_id[<?=$i?>]" type="checkbox" value="<?=$row->category_id?>" 
						<?=(($row->category_id == $_POST["category_id"][$i])?"checked=\"checked\"":"")?> />
            <?=$row->Name?>
          </label>
        </li>
        <?php $i++; } ?>
      </ul>
    </dd>
  </dl>*/
  ?>
  <dl class="clearfix">
    <dt>
      <label class="required">SEF URL (на латиница, без интервали Пример: this-is-test)</label>
    </dt>
    <dd>
      <input class="inputbox w500" name="seo_url" type="text" value="<?=$_POST['seo_url']?>" >
    </dd>
    
    <dt>
      <label for="image" class="required">PDF описание
       
      </label>
    </dt>
    <dd class="inline clearfix">
      <input class="inputbox" name="pdf" type="file" />
      
    </dd>
  </dl>
  
  <label>
    <input class="checkbox" name="published" id="published" type="checkbox" value="1" <?=(($_POST['published'])?"checked=\"checked\"":"")?> />
    Публикуван</label>
  </dd>
  <dd class="submit">
    <input type="submit" name="submit" id="submit" value="създай">
  </dd>
  </dl>
</form>
<?php
	foot_admin(); 
?>
